#!/usr/bin/env python
# -*- coding: utf-8 -*-

from flask import render_template, request, jsonify
from flask_login import login_required, current_user
from models import Issue, Comment
from services.ai_knowledge_service import ai_knowledge_service
from views import main_bp

@main_bp.route('/ai/search', methods=['GET', 'POST'])
@login_required
def ai_search():
    """AI搜索相关问题接口"""
    if request.method == 'POST':
        query = request.form.get('query', '').strip()
        if not query:
            return jsonify({'error': '查询内容不能为空'}), 400
        
        # 获取所有问题
        issues = Issue.query.all()
        
        # 使用AI服务搜索相关问题
        relevant_issues = ai_knowledge_service.search_relevant_issues(query, issues)
        
        # 格式化结果
        results = []
        for score, issue in relevant_issues:
            results.append({
                'id': issue.id,
                'title': issue.title,
                'description': issue.description[:100] + '...' if len(issue.description) > 100 else issue.description,
                'status': issue.status,
                'priority': issue.priority,
                'score': round(score, 2)
            })
        
        return jsonify({'results': results})
    
    return render_template('ai/search.html')

@main_bp.route('/issues/<int:issue_id>/ai-suggestions')
@login_required
def ai_suggestions(issue_id):
    """获取特定问题的AI解决方案建议"""
    # 获取问题和相关评论
    issue = Issue.query.get_or_404(issue_id)
    comments = Comment.query.filter_by(issue_id=issue_id).all()
    
    # 使用AI服务获取解决方案建议
    solutions = ai_knowledge_service.suggest_solutions(issue, comments)
    
    # 获取关键见解
    insights = ai_knowledge_service.extract_key_insights(issue, comments)
    
    # 获取相关问题
    all_issues = Issue.query.filter(Issue.id != issue_id).all()
    query_text = f"{issue.title} {issue.description}"
    relevant_issues = ai_knowledge_service.search_relevant_issues(query_text, all_issues, top_k=3)
    
    return render_template('ai/suggestions.html', 
                          issue=issue, 
                          solutions=solutions, 
                          insights=insights, 
                          relevant_issues=relevant_issues)

@main_bp.route('/api/ai/analyze-text', methods=['POST'])
@login_required
def analyze_text():
    """分析文本内容的API接口"""
    data = request.json
    text = data.get('text', '').strip()
    if not text:
        return jsonify({'error': '文本内容不能为空'}), 400
    
    # 简单的文本分析
    keywords = ai_knowledge_service._extract_keywords(text)  # 注意：这是一个私有方法，实际项目中应该提供公共接口
    
    # 查找可能相关的问题
    issues = Issue.query.all()
    relevant_issues = ai_knowledge_service.search_relevant_issues(text, issues, top_k=3)
    
    # 格式化相关问题
    related_issues = []
    for score, issue in relevant_issues:
        related_issues.append({
            'id': issue.id,
            'title': issue.title,
            'score': round(score, 2)
        })
    
    return jsonify({
        'keywords': keywords,
        'related_issues': related_issues
    })

@main_bp.route('/ai/dashboard')
@login_required
def ai_dashboard():
    """AI知识库仪表板"""
    # 在实际项目中，这里可以显示AI服务的统计信息、使用情况等
    return render_template('ai/dashboard.html')